<?php

namespace IDock\Insurance\ZFIC\Response;

use IDock\Http\Response;
use IDock\IDock\IDockEnums;
use IDock\Insurance\ZFIC\ZFICEnums;
use IDock\Printer\Premium\PremiumBIPrinter;
use IDock\Printer\Premium\PremiumCIPrinter;
use IDock\Printer\Premium\PremiumCoveragePrinter;
use IDock\Printer\Premium\PremiumFactorPrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\Premium\PremiumTaxPrinter;

class InsurancePriceQueryResponse extends AllZFICResponse
{

    public function printerInit(): Response
    {
        $premiumInquiryPrinter = new PremiumInquiryPrinter();

        $premiumInquiryPrinter->success = true;
        $data = $this->get('data', []);
        if (empty($data)) {
            $errorMsg = $this->getBody()['msg'] ?? '';
            $ciDesc = $biDesc = '';
            if (strpos($errorMsg, '交强险') !== false) {
                $ciDesc = $errorMsg;
            }
            if (strpos($errorMsg, '商业险') !== false) {
                $biDesc = $errorMsg;
            }
            if (strpos($errorMsg, '重复投保') !== false) {
                $premiumInquiryPrinter = $this->getRepeatData($premiumInquiryPrinter, $ciDesc, $biDesc);
                $premiumInquiryPrinter->repeatMessage = $errorMsg;
            }
            $premiumInquiryPrinter->repeatInsuredFlg = true;
            if (empty($premiumInquiryPrinter->repeatInsurePrinter['ciStartData']) && empty($premiumInquiryPrinter->repeatInsurePrinter['biStartData'])) {
                $premiumInquiryPrinter->repeatInsuredFlg = false;
                $this->setError($errorMsg);
            }
            $premiumInquiryPrinter->success = false;
            $this->printer = $premiumInquiryPrinter;
            return $this;
        }
        $ciDesc = $data['messageJQX'] ?? '';
        $biDesc = $data['messageSYX'] ?? '';
        if (strpos($this->getError(), '重复投保') !== false) {
            if (strpos($this->getError(), '交强险') !== false) {
                $ciDesc = $this->getError();
            }
            if (strpos($this->getError(), '商业险') !== false) {
                $biDesc = $this->getError();
            }
        }

        if (!preg_match('/重复投保/',$biDesc))  {
            $biDesc = '';
        }

        if (!preg_match('/重复投保/',$ciDesc))  {
            $ciDesc = '';
        }

        //保费金额
        $jqPremium = $syPremium = 0;

        foreach ($data['kindList'] as $val) {
            if ($val['kindCode'] == 'BZ') {
                $jqPremium = $val['premium'];
            } else {
                $syPremium += $val['premium'];
            }
        }
        //商业险重复投保 强校验
        if ($biDesc) {
            $lastBiEndData = $data['syLastYearEndDate'] ?? '';

            $biStartDate = $data['syStartDate'] ?? '';
            if ($lastBiEndData and $biStartDate and ($lastBiEndData > $biStartDate)) {
                $premiumInquiryPrinter = $this->getRepeatData($premiumInquiryPrinter, $ciDesc, $biDesc,$lastBiEndData);
            }
        }
        //交强险重复投保 强校验
        if ($ciDesc) {
            $premiumInquiryPrinter = $this->getRepeatData($premiumInquiryPrinter, $ciDesc, $biDesc);
        }

        //没有金额进入重复投保判断
        if (!$jqPremium and !$syPremium) {
            $premiumInquiryPrinter = $this->getRepeatData($premiumInquiryPrinter, $ciDesc, $biDesc);
        } else {
            $premiumInquiryPrinter->repeatMessage = implode("\r\n" ,[$ciDesc, $biDesc]);
        }

        if ($premiumInquiryPrinter->repeatInsurePrinter['biStartData'] or $premiumInquiryPrinter->repeatInsurePrinter['ciStartData']) {
            $premiumInquiryPrinter->success = false;
            $premiumInquiryPrinter->repeatMessage = implode("\r\n" ,[$ciDesc, $biDesc]);
            $this->printer = $premiumInquiryPrinter;
            return $this;
        }

        $premiumInquiryPrinter->repeatMessage = trim($premiumInquiryPrinter->repeatMessage);

        //扩展参数
        $premiumInquiryPrinter->argc['platOrderNo'] = $data['platOrderNo'] ?? '';
        $premiumInquiryPrinter->argc['businessNo'] = $data['businessNo'] ?? '';
        //交强险
        $premiumInquiryPrinter->inquiryNo = $data['platOrderNo'];//总询价单号
        $ciPremiumPrinter = new PremiumCIPrinter();
        $ciPremiumPrinter->ciPremium = round($jqPremium, 2);//交强险保费
        $ciPremiumPrinter->ciStartData = $data['jqStartDate'] ?? '';//交强险起保日期
        $ciPremiumPrinter->ciEndData = $data['jqEndDate'] ?? '';//交强险终保日期
        $premiumInquiryPrinter->ciPremiumPrinter = $ciPremiumPrinter;

        $carTaxPrinter = new PremiumTaxPrinter();
        $carTaxPrinter->carShipTax = $data['carShipTax']['sumPayTax'] ?? 0;//车船税本年缴税合计
        $carTaxPrinter->thisYearTax = $data['carShipTax']['taxDueActual'] ?? 0;//本年应缴税
        $carTaxPrinter->overdue = $data['carShipTax']['lateFee'] ?? 0;//滞纳金
        $carTaxPrinter->payBackTax = $data['carShipTax']['previousPay'] ?? 0;//往年补缴金额
        $premiumInquiryPrinter->carTaxPrinter = $carTaxPrinter;


        $biPremiumPrinter = new PremiumBIPrinter();
        $biPremiumPrinter->biPremium = round($syPremium, 2);//商业险保费
        $biPremiumPrinter->biStartData = $data['syStartDate'] ?? '';//商业险起保日期
        $biPremiumPrinter->biEndData = $data['syEndDate'] ?? '';//商业险终保日期
        $premiumInquiryPrinter->biPremiumPrinter = $biPremiumPrinter;

        $coverageList = $data['kindList'] ?? [];
        foreach ($coverageList as $row) {
            $coverage = new PremiumCoveragePrinter();
            $coverage->coverageCode = array_search($row['kindCode'], ZFICEnums::$coverageCode);
            $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode];
            $coverage->amount = $row['amount'] ?? 0;
            $coverage->premium = $row['premium'] ?? 0;
            $coverage->basePremium = $row['premium'] ?? 0;//基础保额
            $coverage->discount = round($row['discount'] / 100, 2) ?? 0;//折扣
            $coverage->serviceTimes = $row['serviceTimes'] ?? 0;//服务次数
            $premiumInquiryPrinter->coverageListAppend($coverage);
        }
        //交商系数
        $factorPrinter = new PremiumFactorPrinter();
        if (!empty($data['rateList'])) foreach ($data['rateList'] as $val) {
            if ($val['profitCode'] == 'F03') {
                $premiumInquiryPrinter->ncdFactor = round($val['rate'] / 100, 2);
            } else if ($val['profitCode'] == 'F05') {
                $factorPrinter->ComFactorAppend('自主定价系数', 'selfPricingCoef', round($val['rate'] / 100, 2) ?? '');
            } elseif ($val['profitCode'] == 'F04') {
                $factorPrinter->ComFactorAppend('交强违法系数', 'ciLegalFactor', round($val['rate'] / 100, 2) ?? '');
            } else {
                $factorPrinter->ComFactorAppend($val['profitName'], $val['profitCode'], round($val['rate'] / 100, 2) ?? '');
            }
        }
        if (isset($data['claimList'])) {
            foreach ($data['claimList'] as $key => $val) {
                if ($key == 0) {
                    $key = '';
                }
                $factorPrinter->ComFactorAppend('保险公司' . $key, 'companyId', $val['companyId'] ?? '');
                $factorPrinter->ComFactorAppend('理赔金额' . $key, 'claimAmount', $val['claimAmount'] ?? '');
                $factorPrinter->ComFactorAppend('陪案号' . $key, 'claimNo', $val['claimNo'] ?? '');
                $factorPrinter->ComFactorAppend('出险日期' . $key, 'accidentTime', $val['accidentTime'] ?? '');
                $factorPrinter->ComFactorAppend('结案日期' . $key, 'endcaseTime', $val['endcaseTime'] ?? '');
            }
        }
        $factorPrinter->ComFactorAppend('七炅评分', 'qjGrade', $data['qjGrade'] ?? '');
        $factorPrinter->ComFactorAppend('车慧达评分', 'chdGrade', $data['chdGrade'] ?? '');
        $premiumInquiryPrinter->premiumFactorPrinter = $factorPrinter;


        $this->printer = $premiumInquiryPrinter;
        return $this;
    }

    /**
     * 重复投保
     * @param PremiumInquiryPrinter $premiumInquiryPrinter
     * @param $ciMeg
     * @param $biMeg
     * @param string $lastBiEndData
     * @return PremiumInquiryPrinter
     */
    public function getRepeatData(PremiumInquiryPrinter $premiumInquiryPrinter, $ciMeg, $biMeg, string $lastBiEndData = ''): PremiumInquiryPrinter
    {

        if (preg_match('/交强[\s\S]*终保日期 ([\d\s:-]+)/', $ciMeg, $matches)) {
            if ($matches[1] ?? '') {
                $ciStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $premiumInquiryPrinter->repeatInsurePrinter['ciStartData'] = $ciStartData;
            }
        }

        if ($lastBiEndData) {
            $biStartData = date('Y-m-d H:i:s', strtotime($lastBiEndData));
            $premiumInquiryPrinter->repeatInsurePrinter['biStartData'] = $biStartData;
        } else {
            if (preg_match('/商业[\s\S]*终保日期：(\d{4}-\d{1,2}-\d{1,2})/', $biMeg, $matches)) {
                if ($matches[1] ?? '') {
                    $biStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                    $premiumInquiryPrinter->repeatInsurePrinter['biStartData'] = $biStartData;
                }
            }
        }

        if ($premiumInquiryPrinter->repeatInsurePrinter['ciStartData'] or $premiumInquiryPrinter->repeatInsurePrinter['biStartData']) {
            $premiumInquiryPrinter->repeatInsuredFlg = true;
        }

        return $premiumInquiryPrinter;
    }
}
